#!/usr/bin/env python

from __future__ import print_function

import os
import re
import yaml


def multiple_replace(vars, text):
    regex = re.compile("{{(" + "|".join(re.escape(k) for k in vars) + ")}}")

    return regex.sub(lambda mo: vars.get(mo.group(1)), text)


def main():
    rust_version = open('../rust-toolchain').read().strip()
    template = open('Dockerfile.in').read()

    for root, dirs, files in os.walk('.'):
        if 'config.yaml' in files:
            with open(os.path.join(root, 'config.yaml')) as fp:
                vars = yaml.load(fp, Loader=yaml.FullLoader)
            vars['rust_version'] = rust_version
            with open(os.path.join(root, 'Dockerfile'), 'w') as fp:
                print(multiple_replace(vars, template), file=fp)


if __name__ == '__main__':
    main()
